//
// Created by haoy on 2017/3/16.
//

#include <cstdio>
#include <cstdlib>
#include <cstring>

#include "dbg.hpp"
#include "tlv.hpp"
#include "util.h"

int read_tlv(FILE *fp, unsigned char *buf, int bufsize, int *plength, int *ptype) {
    int ret = 0;
    int type;
    int length;
    int bytes;
    unsigned char t4[4];

    do
    {
        bytes = fread(t4, sizeof(char), 4, fp);
        if(bytes != 4){
            ret = -1;
            break;
        }
        // new tlv format using 4 bytes for T, old was 2 bytes
        type = le_get_u32(t4);
        //dbgi("tlv: type=%d\n", type);

        bytes = fread(t4, sizeof(char), 4, fp);
        if(bytes != 4){
            break;
        }
        length = le_get_u32(t4);
        //dbgi("tlv: length=%d\n", length);

        if(length > bufsize){
            dbge("too big tlv length %d, bufsize=%d\n", length, bufsize);
            ret = -1;
            break;
        } else if (length == 0){
            ret = 0;
            *ptype = type;
            *plength = 0;
            break;
        }

        bytes = fread(buf, sizeof(char), length, fp);
        if(bytes != length){
            ret = -1;
            break;
        }

        *ptype = type;
        *plength = length;

        ret = 0;
    } while (0);
    return ret;
}